package com.gopay.scheduler.job;
 
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.PayBankOpType;
import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlDao;
import com.gopay.common.cps.service.cbrmb.CbRmbAutoSettleHelper;
import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtl;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.cbrmb.Tran01721PortalVO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;
import com.gopay.scheduler.service.cbrmb.CbRmbAutoSettleService;
import com.gopay.scheduler.service.cbrmb.CbRmbPayForCcbService;

/**
 * 跨境人民币境外提现自动结算Job
 * 
 * @CbRmbJwDrawJob.java
 * @author qianld
 * @2016-07-14  下午15:39:35 www.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbJwDrawJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 统计天数，跨境的结算周期有可能是15天，加上最长的节假日7天，天数可以设置为30天
     */
    private static final int STATI_DAYS = 30;

    /**
     * 最近一个月的法定工作日列表
     */
    private List<String> legalWorkList;

    private String startDay;

    private String today;

    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    @Resource(name = "cbRmbAutoSettleService")
    private CbRmbAutoSettleService cbRmbAutoSettleService;

    @Resource(name = "cbRmbAutoSettleHelper")
    private CbRmbAutoSettleHelper cbRmbAutoSettleHelper;

    @Resource(name = "cbRmbTranAssistDtlDao")
    private CbRmbTranAssistDtlDao cbRmbTranAssistDtlDao;
    
    @Resource(name = "cbRmbPayForCcbService")
    private CbRmbPayForCcbService cbRmbPayForCcbService;
    
    @Override
    public void doJobInternal() {
        

        // 当前时间
        Date curDate = new Date();
        
        // 初始化数据
        init(curDate);

//        if (curDate.getMinutes()/5%2==0) {    
//        if (curDate.getHours() < 10) {        
            // 执行4点判断，这个可以在4点启动
            doPayJudge();
//        } else {
//            // 判断今天是否为节假日,节假日不能报盘的
//            if (!cbRmbAutoSettleHelper.isHoliday(curDate)) {
//                // 对当天结算的并且结算日为节假日的T+N订单执行报盘，也可以改个状态让别的定时任务处理也行,这个还没有确定
//                doTenBCDL();
//            }
//        }

       
    }

    /**
     * 初始化数据
     * 
     * @param curDate
     */
    protected void init(Date curDate) {
        // 查询最近一个月的法定工作日
        legalWorkList = cbRmbAutoSettleHelper.queryLegalWorkDayOfRecentOneMonth(curDate);

        logger.error("--legalWorkList=" + legalWorkList.toString());

        // 当前时间
        today = DateUtils.format(curDate, "yyyyMMdd");

        // 计算T-25的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        calendar.add(Calendar.DAY_OF_MONTH, -STATI_DAYS);
        startDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");

        logger.error("--today=" + today + ",startDay=" + startDay);
    }

    /**
     * 将境外提现是今天结算的改为待报盘  state=01
     */
    protected void doPayJudge() {
        // 查询订单之零点判断,这个要修改的sql不对，查询审核通过的,是T+N的
    	//T+0的特殊处理，搞个定时任务10分钟一次处理待报盘的,结算周期是T+0的
        List<CpsGenMainOrder> mainList = cbRmbAutoSettleService.queryOrderOfCbRmbJw(startDay, today);

        logger.error("cbrmb 提现--mainList.size=" + mainList.size());

        // 筛选出结算日为今天的订单
        List<CpsGenMainOrder> orderList = new ArrayList<CpsGenMainOrder>();
        for (CpsGenMainOrder main : mainList) {
            try{
                logger.error("checkTodayIsSettleDay------GopayOrderId=" + main.getGopayOrderId());
                if (checkTodayIsSettleDay(main, main.getTransDtlSq(), today)) {
                    orderList.add(main);
                }
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("checkTodayIsSettleDay Error", e);
            }
        }

        logger.error("跨境人民币境外提现的今天结算的订单个数--orderIdList.size=" + orderList.size());

        // 修改订单状态
        CpsGenMainOrder main;
        for (int i = 0; i < orderList.size(); i++) {
            main = orderList.get(i);

        
            //logger.error("doZeroJudge------GopayOrderId=" + main.getGopayOrderId());
            try {
                //将这些订单的CB_RMB_TRAN_ASSIST_DTL表的报盘状态改为等待报盘01
            CbRmbTranAssistDtl ct=cbRmbTranAssistDtlDao.findByGopayOrderId(main.getGopayOrderId());
            //待报盘
            ct.setState("01");
            	
            cbRmbTranAssistDtlDao.update(ct);	
                
            
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("update CB_RMB_TRAN_ASSIST_DTL Error", e);
            }
        }

    }

    /**
     * 校验今天是否为结算日,跨境人民币境外提现的简单
     * 
     * @param main
     * @param settleCircle
     * @return
     */
    private boolean checkTodayIsSettleDay(CpsGenMainOrder main, int settleCircle, String today) {

        String ruleId = null;

        // 计算结算日
        String settleDay = null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(main.getGopayTxnTm());
        //calendar.add(Calendar.DAY_OF_MONTH, -3);//模拟到3天前
        int count = 0;
        for (int i = 1; i <= STATI_DAYS; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String tmpDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");

            if (legalWorkList.contains(tmpDay)) {
                ruleId=null;
                count++;
            } 

            if (count >= settleCircle) {
                settleDay = tmpDay;
                break;
            }
           
        }

        // 借用属性返回ruleId
        main.setRemark1(ruleId);
        return today.equals(settleDay);
    }

    /**
     * 对当天结算的并且结算日为节假日的T+N订单执行报盘，也可以改个状态让别的定时任务处理也行
     */
    protected void doTenBCDL() {
        // 查询订单之十点银企直连,sql要改呀
        List<CpsGenMainOrder> orderList = cbRmbAutoSettleService.queryOrderOfBCDL(startDay, today);

        logger.error("doTenBCDL--queryOrder--orderList.size=" + orderList.size());


        // 调用接口直接去报盘
        CpsGenMainOrder main;
        for (int i = 0; i < orderList.size(); i++) {
            main = orderList.get(i);

           
            logger.error("doTenBCDL------GopayOrderId=" + main.getGopayOrderId());
            try {
                // 调用cps
            	CbRmbTranAssistDtl cbrmb=new CbRmbTranAssistDtl();
            	cbRmbPayForCcbService.payForCcb(cbrmb);
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("跨境人民币提现报盘出现错误,订单号:"+main.getGopayOrderId(), e);
            }
        }
    }

}
